//                 _              
//                | |             
//   __ _ _ __ ___| |__ __  _____ 
//  / _` | '__/ __| '_ \\ \/ / __|
// | (_| | | | (__| | | |>  <\__ \
//  \__,_|_|  \___|_| |_/_/\_\___/
//                                
// Copyright 2010 Scott Dixon http://www.archxs.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package com.archxs.commons;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.junit.Test;

import com.someoneelse.TestVariantExtension;

public class VariantObjectCacheTest {

    @Test
    public void testCachedNull() {
        Assert.assertSame(Variant.valueOf((String)null), Variant.valueOf((String)null));
        Assert.assertSame(Variant.valueOf((String[])null), Variant.valueOf((String[])null));
    }
    
    @Test
    public void testObjectCache() {
        VariantObjectCacheFactory.getInstance().clearCache();
        final Variant object0 = Variant.valueOf("foo");
        final Variant object1 = Variant.valueOf("bar");
        final Variant object2 = Variant.valueOf("foo");
        Assert.assertSame(object0,object2);
        Assert.assertNotSame(object0, object1);
    }
    
    @Test
    public void testClearCache() {
        final VariantObjectCache cache = VariantObjectCacheFactory.getInstance();
        cache.clearCache();
        final String foo = "foo";
        Assert.assertNull(cache.getCachedValue(foo));
        final Variant fooVariant = cache.readThroughCache(Variant.class, foo);
        Assert.assertNotNull(fooVariant);
        Assert.assertSame(fooVariant, cache.getCachedValue(foo));
        cache.clearCache();
        Assert.assertNull(cache.getCachedValue(foo));
    }
    
    @Test
    public void testClearCacheOfArrays() {
        final VariantObjectCache cache = VariantObjectCacheFactory.getInstance();
        cache.clearCache();
        final String[] foo = new String[] {"foo0", "foo1"};
        Assert.assertNull(cache.getCachedValue(foo));
        final Variant fooVariant = cache.readThroughCache(Variant.class, foo);
        Assert.assertNotNull(fooVariant);
        Assert.assertSame(fooVariant, cache.getCachedValue(foo));
        cache.clearCache();
        Assert.assertNull(cache.getCachedValue(foo));
    }
    
    /**
     * Ensure the cache does not cache on {@link VariantObjectCache#getCachedValue(String)}
     */
    @Test
    public void testGetterDoesNotCache() {
        final VariantObjectCache cache = VariantObjectCacheFactory.getInstance();
        cache.clearCache();
        final String foo = "testTypedObjectCache";
        Assert.assertNull(cache.getCachedValue(foo));
        Assert.assertNull(cache.getCachedValue(foo));
    }
    
    /**
     * Ensure the cache does not cache on {@link VariantObjectCache#getCachedValue(String)}
     */
    @Test
    public void testGetterDoesNotCacheArrays() {
        final VariantObjectCache cache = VariantObjectCacheFactory.getInstance();
        cache.clearCache();
        final String[] foo = new String[] {"testTypedObjectCache","testGetterDoesNotCacheArrays"};
        Assert.assertNull(cache.getCachedValue(foo));
        Assert.assertNull(cache.getCachedValue(foo));
    }
    
    @Test
    public void testLocalizedObjectCache() {
        VariantObjectCacheFactory.getInstance().clearCache();
        final Variant object0 = Variant.valueOf("foo",Locale.UK);
        final Variant object1 = Variant.valueOf("foo",Locale.GERMAN);
        final Variant object2 = Variant.valueOf("foo",Locale.GERMAN);
        Assert.assertNotSame(object0, object1);
        Assert.assertSame(object1, object2);
    }
    
    /**
     * Ensure the cache "knows" the difference between different Variant sub-classes.
     */
    @Test
    public void testTypedObjectCache() {
        final VariantObjectCache cache = VariantObjectCacheFactory.getInstance();
        cache.clearCache();
        final String foo = "testTypedObjectCache";
        Assert.assertNull(cache.getCachedValue(foo));
        Variant fooRef = cache.readThroughCache(Variant.class, foo);
        Assert.assertNotNull(fooRef);
        Assert.assertSame(fooRef, cache.readThroughCache(Variant.class, foo));
        Assert.assertNotSame(fooRef, cache.readThroughCache(TestVariantExtension.class, foo));
        fooRef = cache.readThroughCache(TestVariantExtension.class, foo);
        Assert.assertSame(fooRef, cache.readThroughCache(TestVariantExtension.class, foo));
        Assert.assertNotSame(fooRef, cache.readThroughCache(Variant.class, foo));
        fooRef = cache.readThroughCache(Variant.class, foo);
        Assert.assertSame(fooRef, cache.readThroughCache(Variant.class, foo));
    }
    
    @Test
    public void testTypedObjectArrayCache() {
        final VariantObjectCache cache = VariantObjectCacheFactory.getInstance();
        cache.clearCache();
        final String foo[] = new String[]{"testTypedObjectCache","testTypedObjectArrayCache"};
        Assert.assertNull(cache.getCachedValue(foo));
        Variant fooRef = cache.readThroughCache(Variant.class, foo);
        Assert.assertNotNull(fooRef);
        Assert.assertSame(fooRef, cache.readThroughCache(Variant.class, foo));
        Assert.assertNotSame(fooRef, cache.readThroughCache(TestVariantExtension.class, foo));
        fooRef = cache.readThroughCache(TestVariantExtension.class, foo);
        Assert.assertSame(fooRef, cache.readThroughCache(TestVariantExtension.class, foo));
        Assert.assertNotSame(fooRef, cache.readThroughCache(Variant.class, foo));
        fooRef = cache.readThroughCache(Variant.class, foo);
        Assert.assertSame(fooRef, cache.readThroughCache(Variant.class, foo));
    }
    
    @Test
    public void testArrayObjectCache() {
        VariantObjectCacheFactory.getInstance().clearCache();
        final Variant object0 = Variant.valueOf(new String[]{"foo","bar"});
        final Variant object1 = Variant.valueOf(new String[]{"bar","foo"});
        final Variant object2 = Variant.valueOf(new String[]{"foo","bar"});
        final Variant object3 = Variant.valueOf(Arrays.toString(new String[]{"foo","bar"}));
        Assert.assertSame(object0,object2);
        Assert.assertNotSame(object0, object1);
        Assert.assertSame(object0,object3);
    }
    
    @Test
    public void testLocalizedArrayObjectCache() {
        VariantObjectCacheFactory.getInstance().clearCache();
        final Variant object0 = Variant.valueOf(new String[]{"foo","bar"},Locale.UK);
        final Variant object1 = Variant.valueOf(new String[]{"foo","bar"},Locale.GERMANY);
        final Variant object2 = Variant.valueOf(new String[]{"foo","bar"},Locale.UK);
        final Variant object3 = Variant.valueOf(Arrays.toString(new String[]{"foo","bar"}),Locale.UK);
        Assert.assertSame(object0,object2);
        Assert.assertNotSame(object0, object1);
        Assert.assertSame(object0,object3);
    }
    
    @Test
    public void testObjectCacheThreadSafety() throws InterruptedException, ExecutionException {
        VariantObjectCacheFactory.getInstance().clearCache();
        
        final int testThreads = 5;
        final int testInsertsPerThread = 1000;
        final ExecutorService stressor = Executors.newFixedThreadPool(testThreads, new ThreadFactory() {

            private int m_threadCount = 0;
            
            @Override
            public Thread newThread(final Runnable r) {
                return new Thread(r, String.format("testObjectCacheThreadSafety_%d", m_threadCount++));
            }
            
        });
        
        final List<Future<Integer> > tasks = new ArrayList<Future<Integer> >();
        final List<Variant> allStrongRefs = new ArrayList<Variant>();
        for(int i = 0; i < testThreads; ++i) {
            tasks.add(stressor.submit(new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                    int cacheMisses = 0;
                    final Variant[] strongRefs = new Variant[testInsertsPerThread];
                    for(int i = 0; i < testInsertsPerThread; ++i) {
                        strongRefs[i] = Variant.valueOf(String.format("%s::0x%s", Thread.currentThread().getName(), Integer.toHexString(i)));
                        allStrongRefs.add(strongRefs[i]);
                        Thread.yield();
                    }
                    final VariantObjectCache objectCache = VariantObjectCacheFactory.getInstance();
                    for(final Variant variant : strongRefs) {
                        if (null == objectCache.getCachedValue(variant.toString(), variant.getLocale())) {
                            ++cacheMisses;
                        }
                        Thread.yield();
                    }
                    return cacheMisses;
                }
                
            }));
        }
        
        stressor.shutdown();
        Assert.assertTrue(stressor.awaitTermination(30, TimeUnit.SECONDS));
        int totalCacheMisses = 0;
        for(final Future<Integer> task : tasks) {
            totalCacheMisses += task.get();
        }
        Assert.assertEquals(0, totalCacheMisses);
        Assert.assertEquals(allStrongRefs.size(), VariantObjectCacheFactory.getInstance().getCacheSize(), 10);
        VariantObjectCacheFactory.getInstance().clearCache();
        Assert.assertEquals(0, VariantObjectCacheFactory.getInstance().getCacheSize());
    }
}
